package bank_access;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
import java.util.logging.Logger;

/**
 * @author  Mariusz, Pascal
 * 
 * A KontoSkeleton is an account representation on the bank side, <br>i.e.
 * a skeleton class takes the incoming messages for an account from the middleware
 * and passes it to a skeleton handler which transforms the message into an operation 
 * on the account.
 * 
 * To make sure nothing strange happens during a bank transfer other operations are blocked
 * while one operation is performed. This is assured by a semaphore.
 * 
 * The semaphore is implemented in the middleware since the account interface is fix and cannot
 * be extended by semaphore operations. Each account has its own KontoSkeleton. 
 */
public class KontoSkeleton extends Thread {

    private KontoImplBase konto;
    private int port;
    private ServerSocket serverSocket;
    private ExecutorService threadPool =
            Executors.newFixedThreadPool(3);
    private Logger logger;
    
    public KontoSkeleton(Object konto, int port) {
        logger = Kommunikationsmodul.getLogger();
        if(konto instanceof KontoImplBase){
        	this.konto = (KontoImplBase)konto;
        } else {
        	throw new IllegalArgumentException("Konto ist nicht vom Typ KontoImplBase");
        }
        this.port = port; 
    }

    /**
     * Lausche auf Port und tue was er sagt
     */
    @Override
    public void run() {
        try {
            serverSocket = new ServerSocket(port);
            logger.info("Lausche auf Port " + port);
            while (true) {
                Socket connectionSocket = serverSocket.accept();
                logger.info("Verbindung aufgenommen zu " + connectionSocket.getInetAddress().getCanonicalHostName());
                threadPool.execute(new KontoSkeletonTask(konto, connectionSocket));
            }
        } catch (IOException e) {
            logger.info("IOException");
        }
    }
}

